﻿namespace StyleCop.CSharp.JslRefactoringRules
{
    /// <summary>
    /// A rule to check for comparisons to boolean constants.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Dont", Justification = "Already named the class and don't feel like changing it.")]
    public class DontCompareToBooleanConstant : CsRuleBase<RuleAnalyzer>
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="DontCompareToBooleanConstant"/> class.
        /// </summary>
        /// <param name="analyzer">The analyzer.</param>
        public DontCompareToBooleanConstant(RuleAnalyzer analyzer)
            : base(analyzer)
        {
        }
        #endregion Constructors

        #region Public Methods
        /// <summary>
        /// Analyzes the document.
        /// </summary>
        public override void AnalyzeDocument()
        {
            if (this.Analyzer.IsRuleEnabled(this.Document, RuleAnalyzer.DontCompareToBooleanConstant))
            {
                this.Document.WalkDocument(null, null, this.AnalyzeExpression);
            }
        }
        #endregion Public Methods

        #region Private Methods
        /// <summary>
        /// Analyzes the expression.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <param name="parentExpression">The parent expression.</param>
        /// <param name="parentStatement">The parent statement.</param>
        /// <param name="parentElement">The parent element.</param>
        /// <param name="context">The context.</param>
        /// <returns>Always returns <c>true</c>.</returns>
        private bool AnalyzeExpression(Expression expression, Expression parentExpression, Statement parentStatement, CsElement parentElement, object context)
        {
            RelationalExpression relationalExpression = expression as RelationalExpression;
            if (relationalExpression != null)
            {
                if (relationalExpression.LeftHandSide.IsBooleanConstant()
                    || relationalExpression.RightHandSide.IsBooleanConstant())
                {
                    this.AddViolation(
                        expression.ParentElement(),
                        expression.LineNumber,
                        RuleAnalyzer.DontCompareToBooleanConstant);
                }
            }

            return true;
        }
        #endregion Private Methods
    }
}